package com.bjdd.jdy.baidu;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bjdd.jdy.Constant;
import com.bjdd.jdy.base.RxManager;
import com.bjdd.jdy.entity.RoutePoint;
import com.bjdd.jdy.util.L;
import com.bjdd.jdy.util.T;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/7.
 */

public class NaviUtils {
    public static volatile NaviUtils instance;
    public static List<Activity> activityList = new LinkedList<Activity>();
    private static final String APP_FOLDER_NAME = "BNSDKSimpleDemo";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    public static final String SHOW_CUSTOM_ITEM = "showCustomItem";
    public static final String RESET_END_NODE = "resetEndNode";
    public static final String VOID_MODE = "voidMode";
    private String mSDCardPath = null;

    private static final String[] authBaseArr = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private static final String[] authComArr = {Manifest.permission.READ_PHONE_STATE};
    private static final int authBaseRequestCode = 1;
    private static final int authComRequestCode = 2;

    private boolean hasInitSuccess = false;
    private boolean hasRequestComAuth = false;
    private Context mContext;
    private RoutePoint point;
    private Activity activity ;
    private RxManager rxManager;

    public static NaviUtils getInstance(Activity activity) {
        if (instance == null) {
            synchronized (NaviUtils.class) {
                instance = new NaviUtils(activity);
            }
        }
        return instance;
    }

    private NaviUtils(Activity activity) {
        this.activity = activity;
        mContext = activity;
        rxManager = new RxManager();
    }

    public void start(RoutePoint p){
        rxManager.post(Constant.SHOW_LOADING,false);
        this.point = p;
        if (initDirs()){
            initNavi();
        }
    }
    String authinfo = null;
    private void initNavi() {
        //申请权限
        L.d("initNavi");
        if (Build.VERSION.SDK_INT >= 23) {
            if (!hasBasePhoneAuth()){
                activity.requestPermissions(authBaseArr, authBaseRequestCode);
                return;
            }
        }
        BaiduNaviManager.getInstance().init(activity, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int i, String s) {
                if (i == 0){
                    authinfo = "key校验成功！";
                }else {
                    authinfo = "key校验失败，" + s;
                }
                L.d(authinfo);
            }

            @Override
            public void initStart() {
                L.d("百度导航引擎初始化开始");

            }

            @Override
            public void initSuccess() {
                L.d("百度导航引擎初始化成功");
                hasInitSuccess = true;
                initSetting();
                routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
            }

            @Override
            public void initFailed() {
                L.d("百度引擎初始化失败");
            }
        },null,ttsHandler,ttsPlayStateListener);
    }
    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    // showToastMsg("Handler : TTS play start");
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    // showToastMsg("Handler : TTS play end");
                    break;
                }
                default:
                    break;
            }
        }
    };
    private void initSetting() {
        // BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
        BNaviSettingManager
                .setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, "9516945");
        BNaviSettingManager.setNaviSdkParam(bundle);
    }
    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
            // showToastMsg("TTSPlayStateListener : TTS play end");
        }

        @Override
        public void playStart() {
            // showToastMsg("TTSPlayStateListener : TTS play start");
        }
    };
    private BNRoutePlanNode.CoordinateType mCoordinateType = null;
    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType){
        L.d("开启导航");
        mCoordinateType = coType;
        if (!hasInitSuccess){
            T.show("还未初始化");
        }
        //权限申请
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // 保证导航功能完备
            if (!hasCompletePhoneAuth()) {
                if (!hasRequestComAuth) {
                    hasRequestComAuth = true;
                    activity.requestPermissions(authComArr, authComRequestCode);
                    return;
                } else {
                    T.show("没有设备的权限");
                    //Toast.makeText(BNDemoMainActivity.this, "没有完备的权限!", Toast.LENGTH_SHORT).show();
                }
            }

        }

        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        L.d("设置起始点");
        sNode = new BNRoutePlanNode(point.getStartLng(), point.getStartLat(), "起点", null, coType);
        eNode = new BNRoutePlanNode(point.getEndLng(), point.getEndLat(), "终点", null, coType);
        if(sNode != null && eNode != null){
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            L.d("开启导航界面");

            BaiduNaviManager.getInstance().launchNavigator(activity, list, 1, true, new DemoRoutePlanListener(eNode));

        }

    }
    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            L.d("构造函数DemoRoutePlanListener");
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            /*
             * 设置途径点以及resetEndNode会回调该接口
             */
            L.d("跳转到导航页");
            for (Activity ac : activityList) {

                if (ac.getClass().getName().endsWith("BNDemoGuideActivity")) {
                    return;
                }
            }
            L.d("算路完成");
            Intent intent = new Intent(activity, BNDemoGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            activity.startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            // TODO Auto-generated method stub
            L.d("算路失败");
            rxManager.post(Constant.HIDE_LOADING,false);
            T.show("算路失败");
            //Toast.makeText(BNDemoMainActivity.this, "算路失败", Toast.LENGTH_SHORT).show();
        }
    }
    private boolean hasBasePhoneAuth() {
        PackageManager pm = activity.getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, activity.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private boolean hasCompletePhoneAuth() {
        PackageManager pm = activity.getPackageManager();
        for (String auth : authComArr) {
            if (pm.checkPermission(auth, activity.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    private boolean initDirs(){
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null){
            return false;
        }
        File f = new File(mSDCardPath,APP_FOLDER_NAME);
        if (!f.exists()){
            try {
                f.mkdir();
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
    private String getSdcardDir(){
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)){
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

}
